﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Irandeb4.Models;
using System.Web.Security;
//using System.Data.Entity;

namespace Irandeb4.Controllers
{
    public class UserController : Controller
    {
        private IrandebEntities db = new IrandebEntities();


        //[Authorize(Roles = "Administrator")]
        public ActionResult Register()
        {
            ViewBag.UserRoleId = new SelectList(db.UsersRoles, "UserRoleId", "Role");
            ViewBag.LegendLabel = "Empleado";
            return View();
        }


        //[Authorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult Register(User user)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(user.UserName, user.Password, user.Email, "question", "answer", true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    //FormsAuthentication.SetAuthCookie(user.UserName, false /* createPersistentCookie */); 

                    Roles.AddUserToRole(user.UserName, db.UsersRoles.Find(user.UserRoleId).Role);
                    user.Active = true;
                    db.Users.Add(user);
                    db.SaveChanges();
                    return RedirectToAction("Search", "User");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.UserRoleId = new SelectList(db.UsersRoles, "UserRoleId", "Role" , user.UserRoleId);
            return View(user);
        }

        public ViewResult MyDetails()
        {
            IEnumerable<User> users = from c in db.Users
                                      where c.UserName == User.Identity.Name
                                      select c;

            User user = users.ElementAtOrDefault(0);
            ViewBag.LegendLabel = "Empleado";
            return View("Details",user);
        }
        
        [Authorize(Roles = "Administrator,Employee")]
        public ViewResult Details(int id)
        {
            User user = db.Users.Find(id);
            ViewBag.LegendLabel = "Empleado";
            return View(user);
        }


        public void EditMyInfo()
        {
            IEnumerable<User> users = from c in db.Users
                                      where c.UserName == User.Identity.Name
                                      select c;

            User user = users.ElementAtOrDefault(0);
            ViewBag.UserRoleId = new SelectList(db.UsersRoles, "UserRoleId", "Role", user.UserRoleId);
            ViewBag.LegendLabel = "Empleado";
            RedirectToAction("Details(user.UserId)");
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Edit(int id)
        {
            User user = db.Users.Find(id);
            ViewBag.UserRoleId = new SelectList(db.UsersRoles, "UserRoleId", "Role", user.UserRoleId);
            ViewBag.LegendLabel = "Empleado";
            try
            {
                Roles.RemoveUserFromRole(user.UserName, db.UsersRoles.Find(user.UserRoleId).Role);
            }
            catch { }
            return View(user);
        }


        //[Authorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult Edit(User user)
        {
            ViewBag.LegendLabel = "Empleado";

            if (ModelState.IsValid)
            {
                User userToSave = db.Users.Find(user.UserId);

                userToSave.UserRoleId = user.UserRoleId;

                userToSave.Employee.Ci = user.Employee.Ci;
                userToSave.Employee.Names = user.Employee.Names;
                userToSave.Employee.Surnames = user.Employee.Surnames;
                userToSave.Employee.Email = user.Employee.Email;
                userToSave.Employee.Cellphone = user.Employee.Cellphone;
                userToSave.Employee.Address = user.Employee.Address;
                userToSave.Employee.Position = user.Employee.Position;

                db.SaveChanges();
                Roles.AddUserToRole(user.UserName, db.UsersRoles.Find(user.UserRoleId).Role);
                IEnumerable<User> users = from c in db.Users
                                              where c.UserName == User.Identity.Name
                                              select c;
                User actualUser = users.ElementAtOrDefault(0);
                if (actualUser.UserRole.Role == "Administrator")
                    return RedirectToAction("Search");
                else
                    return RedirectToAction("Index","Home");
            }
            ViewBag.UserRoleId = new SelectList(db.UsersRoles, "UserRoleId", "Role", user.UserRoleId);
            return View(user);
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Delete(int id)
        {
            User user = db.Users.Find(id);
            ViewBag.LegendLabel = "Empleado";
            return View(user);
        }


        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult Delete(int id, User user)
        {
            User userToChange = db.Users.Find(id);
            userToChange.Active = user.Active;
            db.SaveChanges();
            return RedirectToAction("Search");
        }


        [Authorize(Roles = "Administrator")]
        public ActionResult Search()
        {
            var users = db.Users;
            return View(users.ToList());
        }


        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult Search(String toSearch, String searchCriteria)
        {
            List<User> results = new List<User>();
            foreach (var user in db.Users)
            {
                if (user.UserName.Contains(toSearch) || user.Email.Contains(toSearch))
                {
                    if (searchCriteria == "active" && user.Active)
                        results.Add(user);
                    if (searchCriteria == "inactive" && !user.Active)
                        results.Add(user);
                    if (searchCriteria == "all")
                        results.Add(user);
                }
            }

            foreach (var employee in db.Employees)
            {
                if (employee.Names.Contains(toSearch) || employee.Surnames.Contains(toSearch) || employee.Email.Contains(toSearch))
                {
                    //User user = db.Users.Find(employee.EmployeeId);
                    IEnumerable<User> users = from c in db.Users
                                                     where c.EmployeeId == employee.EmployeeId
                                                     select c;

                    User user = users.ElementAtOrDefault(0);
                    bool exists = false;
                    foreach (var usersSelected in results)
                    {
                        if (user!=null && usersSelected.UserId == user.UserId)
                            exists = true;

                    }
                    if (user != null && !exists)
                    {
                        if (searchCriteria == "active" && user.Active)
                            results.Add(user);
                        if (searchCriteria == "inactive" && !user.Active)
                            results.Add(user);
                        if (searchCriteria == "all")
                            results.Add(user);
                    }

                }
            }

            return View(results);
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "El nombre de usuario ya existe. porfavor Introduzca un nombre de usuario diferente.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "Un nombre de usuario esta asociado al email. porfavor introduzca un email diferente.";

                case MembershipCreateStatus.InvalidPassword:
                    return "el password es invalido. porfavor introduzca un password valido.";

                case MembershipCreateStatus.InvalidEmail:
                    return "el email es invalido. Porfavor revise y velva a introducir";

                case MembershipCreateStatus.InvalidAnswer:
                    return "La respuesta de recuperación de password proporcionada no es válida. Por favor, compruebe el valor y vuelva a intentarlo.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "La pregunta de recuperación de contraseña proporcionada no es válida. Por favor, compruebe el valor y vuelva a intentarlo.";

                case MembershipCreateStatus.InvalidUserName:
                    return "El nombre de usuario proporcionado no es válido. Por favor, compruebe el valor y vuelva a intentarlo.";

                case MembershipCreateStatus.ProviderError:
                    return "El proveedor de autenticación devovio un error. Por favor, verifique su entrada y vuelva a intentarlo. Si el problema persiste, póngase en contacto con su administrador de sistema.";

                case MembershipCreateStatus.UserRejected:
                    return "La solicitud de creación ha sido cancelada. Por favor, verifique su entrada y vuelva a intentarlo. Si el problema persiste, póngase en contacto con su administrador de sistema.";

                default:
                    return "Ocurrió un error desconocido. Por favor, verifique su entrada y vuelva a intentarlo. Si el problema persiste, póngase en contacto con su administrador de sistema.";
            }
        }
        #endregion

    }
}
